package com.trade.system.security;

import com.trade.module.base.entity.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Class Description: 安全的用戶
 *
 * @Version v1.0 2017/4/22 2:15
 * @JDK version 1.8.0_51
 * @Author zfb
 */
public class SecurityUser extends User implements UserDetails {

    private static final long serialVersionUID = -2292495510566048320L;

    /**
     * 声明放置用户角色的集合’
     **/
    private List<String> roles;

    /**
     * 记住登录的用户
     *
     * @param user  用戶
     * @param roles 角色編碼集合（ROLE_TRUSTED_CLIENT）
     */
    SecurityUser(User user, List<String> roles) {
        if (null != user) {
            this.setId(user.getId());
            this.setAccount(user.getAccount());
            this.setPassWord(user.getPassWord());
            this.roles = roles;
        }
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // 根据自定义逻辑来返回用户权限，如果用户权限返回空
        // 或者和拦截路径对应权限不同，验证不通过
        List<SimpleGrantedAuthority> authorities=new ArrayList<SimpleGrantedAuthority>();
        for (String role : roles) {
            authorities.add(new SimpleGrantedAuthority(role));
        }
        return authorities;
    }

    @Override
    public String getPassword() {
        return super.getPassWord();
    }

    @Override
    public String getUsername() {
        return super.getAccount();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
